using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WindowsPhonePostClient;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace LyonMag
{
    public partial class UserComments : PhoneApplicationPage
    {
        Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        string id = string.Empty;
        private App app = App.Current as App;
       
        public UserComments()
        {
            try
            {
                InitializeComponent();
            
               
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                List<Cinema.ForumComments> obj = new List<Cinema.ForumComments>();
                NavigationContext.QueryString.TryGetValue("id",out id);
                for (int i = 0; i < app.lst_Forum.Count(); i++)
                {
                    if (app.lst_Forum[i].Id == id)
                    {
                      for(int k=0;k<app.lst_Forum[i].forum_comments.Count();k++)
                      {
                          obj.Add(new Cinema.ForumComments() { Comment_name = "Déposé par : " + " " + app.lst_Forum[i].forum_comments[k].Comment_name  + "  le " + DateTime.Parse(app.lst_Forum[i].forum_comments[k].comment_date).ToString("dd MM yyyy  HH:mm:ss"), Comment_text = app.lst_Forum[i].forum_comments[k].Comment_text });
                    }
                    }

                }

                List<Cinema.ForumComments> newtest = obj.ToList();
                newtest.Reverse();
                lstForum.ItemsSource = newtest;
            //  lstForum.ItemsSource = obj;
                if (App.appSettingsGuid["accoutid"].ToString()!= "test")
                {
                    btnLogout.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }

        public void userregister()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("username", txtUserName.Text);
            string userpassword = Base64Encode(txtPasswor.Password);
            parameters.Add("email", txtEmail.Text);
            parameters.Add("password", userpassword);

            PostClient proxy = new PostClient(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {

                    string data = e.Result;

                    //JsonConvert.PopulateObject(e.Result.ToString(), obj_udistibuteurserreg);


                    if (data == "0 Ce nom d'utilisateur est réservé ou incorrect. Connectez-vous s'il s'agit du votre.")
                    {
                        popLogins.IsOpen = true;
                        popAlert.IsOpen = false;
                        popRigister.IsOpen = false;
                        poplogout.IsOpen = false;
                        popNickName.IsOpen = false;
                       
                       // MessageBox.Show("Ce nom d'utilisateur est réservé ou incorrect. Connectez-vous s'il s'agit du votre");

                    }
                    else
                    {
                        popAlert.IsOpen = true;
                        popRigister.IsOpen = false;
                        App.appSettingsGuid["accoutid"] = data.ToString();
                        App.appSettingsGuid.Save();
                        txtUserComments.Text = "";
                        btnLogout.Visibility = Visibility.Visible;
                       
                       
                    }

                }
            };
            proxy.DownloadStringAsync(new Uri(" http://www.lyonmag.com/win8/register", UriKind.Absolute));
        }
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }
        public void userlogin()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("login", txtUsernamePassword.Text);
            // string heypassord = GetRandomAlphaNumeric;
            string encryptedpassowrd = "k9" + txtPasswordPassword.Password;
            string userpassword = Base64Encode(encryptedpassowrd);
            //  parameters.Add("email", txtUsernamePassword.Text);
            parameters.Add("password", userpassword);

            PostClient proxy = new PostClient(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    //Process the result...
                    string data = e.Result;

                    //JsonConvert.PopulateObject(e.Result.ToString(), obj_userreg);



                    if (data != "ko")
                    {
                        App.appSettingsGuid["accoutid"] = data.ToString();
                        App.appSettingsGuid.Save();
                        popLogin.IsOpen = false;
                        popNickName.IsOpen = true;
                        popSubmit.IsOpen = false;
                        btnLogout.Visibility = Visibility.Visible;
                        postforum();
                       // MessageBox.Show("Votre compte a bien été créé. Un email de confirmation vient de vous être envoyé.\n\nPour poster des commentaires avec un compte différent, cliquez sur le bouton de déconnexion qui vient d'apparaître en haut de l'écran");
                    }
                    else
                    {
                      //  MessageBox.Show(" Login ou mot de passe incorrect (si vous avez oublié votre mot de passe, rendez-vous sur notre site www.lyonmag.com)");
                        txtUserName.Text = txtNickName.Text;
                        popLoginFailed.IsOpen = true;
                      //  popRigister.Visibility = Visibility.Visible;
                        popNickName.IsOpen = false;

                    }

                }
            };
            proxy.DownloadStringAsync(new Uri("http://www.lyonmag.com/win8/login", UriKind.Absolute));
        }

        public void postforum()
        {
          
            if (App.appSettingsGuid["accoutid"].ToString() != "test")
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();

                parameters.Add("action", "add_comment");


                parameters.Add("id", id);
                parameters.Add("type", "article");
                if (App.appSettingsGuid["username"].ToString() != "testuser")
                {
                    parameters.Add("name", App.appSettingsGuid["username"].ToString());
                }
                else
                {
                    parameters.Add("name", txtNickName.Text);
                }
                if (App.appSettingsGuid["accoutid"].ToString() == "test")
                {
                    parameters.Add("account_id", string.Empty);
                }
                else
                {
                    parameters.Add("account_id", App.appSettingsGuid["accoutid"]);
                }

                parameters.Add("text", txtUserComments.Text);

                PostClient proxy = new PostClient(parameters);
                proxy.DownloadStringCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        //Process the result...
                        string data = e.Result;



                        if (data == "0 Ce nom d'utilisateur est r�serv� ou incorrect. Connectez-vous s'il s'agit du votre.")
                        {
                            popLogins.IsOpen = true;
                            popNickName.IsOpen = false;
                        }
                        else
                        {

                        //    MessageBox.Show(e.Result.ToString());
                            popNickName.IsOpen = false;
                            popLogin.IsOpen = false;
                            popRigister.IsOpen = false;
                            popLogins.IsOpen = false;
                            popSecond.IsOpen = true;
                           // this.NavigationService.GoBack();
                           
                        }




                    }
                };
                proxy.DownloadStringAsync(new Uri("http://www.lyonmag.com/win8/comment", UriKind.Absolute));
            }
            else
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();

                parameters.Add("action", "add_comment");


                parameters.Add("id", id);
                parameters.Add("type", "article");
                parameters.Add("name", txtNickName.Text);
                if (App.appSettingsGuid["accoutid"].ToString() == "test")
                {
                    parameters.Add("account_id", string.Empty);
                }
                else
                {
                    parameters.Add("account_id", App.appSettingsGuid["accoutid"]);
                }

                parameters.Add("text", txtUserComments.Text);

                PostClient proxy = new PostClient(parameters);
                proxy.DownloadStringCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        //Process the result...
                        string data = e.Result;



                        if (data == "0 Ce nom d'utilisateur est r�serv� ou incorrect. Connectez-vous s'il s'agit du votre.")
                        {
                            popLogins.IsOpen = true;
                            popNickName.IsOpen = false;
                        }
                        else
                        {
                            popSubmit.IsOpen = true;
                            popNickName.IsOpen = false;
                        }




                    }
                };
                proxy.DownloadStringAsync(new Uri("http://www.lyonmag.com/win8/comment", UriKind.Absolute));
            }

        }
        private void btnMainSubmit_Click(object sender, RoutedEventArgs e)
        {
            popLogin.IsOpen = true;
        }

        private void btnCancl_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            popNickName.IsOpen = false;
            popNickName.IsOpen = false;
            popLogins.IsOpen = false;
            popRigister.IsOpen = false;
        }

        private void btnEnter_Click(object sender, RoutedEventArgs e)
        {
            if (txtNickName.Text != "")
            {

                postforum();


            }
            else
            {
                MessageBox.Show("Vous devez saisir un pseudo !");
            }
        }


        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationBar.IsVisible = false;
                App.appSettingsGuid["accoutid"] = "test";
                App.appSettingsGuid.Save();
            }
            catch (Exception ex)
            {
                ApplicationBar.IsVisible = false;
                App.appSettingsGuid["accoutid"] = "test";
                App.appSettingsGuid.Save();
                ex.Message.ToString();
            }
        }
     
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            popRigister.IsOpen = true;
            popRigister.Visibility = Visibility.Visible;
            popSubmit.IsOpen = false;
            txtUserName.Text = txtNickName.Text;
            txtUsernamePassword.Text = txtNickName.Text;
        }

        private void btnTryAgain_Click(object sender, RoutedEventArgs e)
        {
            popLogin.IsOpen = false;
            popNickName.IsOpen = true;
            popSubmit.IsOpen = false;
            popRigister.IsOpen = false;
            this.NavigationService.GoBack();
        }

        private void btnLoginCancel_Click(object sender, RoutedEventArgs e)
        {
           // txtUsernamePassword.Text = txtNickName.Text;
            popLogin.IsOpen = false;
        }

        private void btnLoginUser_Click(object sender, RoutedEventArgs e)
        {
            userlogin();
        }
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {

            if (App.appSettingsGuid["accoutid"].ToString() != "test")
            {
                postforum();
            }
            else
            {
                popNickName.IsOpen = true;
            }
            
        }

        private void btnArticle_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Forumarticle.xaml?id=" + id, UriKind.RelativeOrAbsolute));

        }

        private void btnCancelRegister_Click(object sender, RoutedEventArgs e)
        {
            popRigister.IsOpen = false;
            popLogin.IsOpen = false;
          
            popNickName.IsOpen = false;
            popSubmit.IsOpen = false;
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            popNickName.Visibility = Visibility.Collapsed;
            if (regex.Match(txtEmail.Text.Trim()).Success)
            {
                userregister();
            }
            else
            {
                popEMail.IsOpen = true;
            }
         
        }

        private void imgRefresh_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/postforum.xaml", UriKind.RelativeOrAbsolute));
        }

        private void btnLogout_Click(object sender, RoutedEventArgs e)
        {
            App.appSettingsGuid["accoutid"] = "test";
            App.appSettingsGuid.Save();
            poplogout.IsOpen = true;
            btnLogout.Visibility = Visibility.Collapsed;

        }
        private void btnTrynew_Click(object sender, RoutedEventArgs e)
        {
            popNickName.IsOpen = true;
            popLogins.IsOpen = false;
        }

        private void btnLoginnew_Click(object sender, RoutedEventArgs e)
        {
            txtUsernamePassword.Text = txtNickName.Text;
            popLogins.IsOpen = false;
            popLogin.IsOpen = true;
            popNickName.IsOpen = false;
        }

        private void btnAlert_Click(object sender, RoutedEventArgs e)
        {
            popAlert.IsOpen = false;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            poplogout.IsOpen = false;
        }

        private void btnCloseSecond_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
        }

        private void popValidEmail_Click(object sender, RoutedEventArgs e)
        {
            popEMail.IsOpen = false;
        }

        private void btnFermerloginfailed_Click(object sender, RoutedEventArgs e)
        {
            popLoginFailed.IsOpen = false;
        }
    }
}